package extraProblem;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//Comparable接口，并重写compareTo方法可以在方法体中自定义比较规则
//包装类一般都实现了Comparable接口，并已经重写了该方法
public class TestComparable {
	public static void main(String[] args) {
	/*List l1=new ArrayList();
	l1.add(199);
	l1.add(15);
	l1.add(98);
	System.out.println(l1);
	Collections.sort(l1);//Collections工具类的方法
	System.out.println(l1);*/
	Student s1=new Student("张三",65);
	Student s2=new Student("李四",35);
	Student s3=new Student("王五",12);
	List l2=new ArrayList();
	
	l2.add(s1);
	l2.add(s2);
	l2.add(s3);
	System.out.println(l2);
	//报错：Exception in thread "main" java.lang.ClassCastException:（Student类没有实现Comparable接口时）
	//extraProblem.Student cannot be cast to java.lang.Comparable
	Collections.sort(l2);
	System.out.println(l2);
	}	
}
class Student implements Comparable{
	String name;
	int grade;//根据成绩排名
	public Student(String name,int grade){
		this.name=name;
		this.grade=grade;
	}
	@Override
	public int compareTo(Object o) {
		// TODO Auto-generated method stub
		Student s=(Student)o;
		return this.grade-s.grade;
	}
	public String  toString(){
		return this.name+" "+this.grade;
	}
}
